package com.lieve.tomcat;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author sunlijiang
 * @date 2020/3/26
 */
@Component
public class ThreadPoolExectorService {

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    public Integer getMaxWorkTime() {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        List<Future<Integer>> futureList = new ArrayList<>();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("Hello");
        for (int i = 0; i < 10; i++) {
            Random random = new Random();
            threadPoolTaskExecutor.submit(new Worker(random.nextInt(10), countDownLatch));
        }
        try {
            countDownLatch.await();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Integer maxValue = 0;
        try {
            for (Future<Integer> future : futureList) {
                Integer result = future.get();
                System.out.println(" result : " + result);
                maxValue = result > maxValue ? result : maxValue;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
        return maxValue;
    }

    class Worker implements Callable<Integer> {

        private int workTime;
        private CountDownLatch countDownLatch;

        public Worker(int workTime, CountDownLatch countDownLatch) {
            this.workTime = workTime;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public Integer call() throws Exception {
            System.out.println(System.currentTimeMillis() + " " +  workTime);
            Thread.sleep(workTime * 1000);
            countDownLatch.countDown();
            return workTime;
        }
    }
}
